package com.wms.interceptor;

import com.google.gson.Gson;
import com.wms.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import com.wms.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
//实现拦截器
public class LonginCheckInterceptor implements HandlerInterceptor {
    //json格式转换函数
    @Autowired
    private Gson gson;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求的url
        String url = request.getRequestURI().toString();
        log.info("请求的url:{}", url);
        //2.获取请求头中的令牌（token）
        String jwt = request.getHeader("token");
        //3.判断令牌是否为空，如果为空，则返回错误结果（未登录）
        if (!StringUtils.hasLength(jwt)){
            log.info("未找到登录信息");
            Result error = Result.error("login failed");
            String Not_login = gson.toJson(error);
            response.getWriter().write(Not_login);
            return false;
        }
        //4.解析token如果解析失败也不予以放行
        try {
            JwtUtils.parseJwt(jwt);
        }catch (Exception e){
            log.info("token解析失败");
            Result error = Result.error("token_Parsing failure");
            String Not_login = gson.toJson(error);
            response.getWriter().write(Not_login);
            return false;
        }
        //5.放行
        log.info("令牌解析成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LonginCheckInterceptor postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LonginCheckInterceptor afterCompletion");
    }
}
